<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>内网设备扫描工具</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css" rel="stylesheet">
    <link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet">
</head>
<body>
    <div class="container mt-4">
        <div class="card mb-4">
            <div class="card-body">
                <div class="d-flex align-items-center mb-4">
                    <img src="{{ url_for('static', filename='img/logo.svg') }}" alt="Logo" class="me-3" style="height: 32px;">
                    <h2 class="card-title mb-0">
                        <i class="fas fa-network-wired me-2"></i>内网设备扫描工具
                    </h2>
                </div>
                <div class="row g-3 align-items-center">
                    <div class="col-md-7">
                        <div class="input-group">
                            <span class="input-group-text bg-light"><i class="fas fa-search"></i></span>
                            <input type="text" id="network" class="form-control" placeholder="输入网段 (例如: 192.168.1.0/24)">
                        </div>
                    </div>
                    <div class="col-md-5 d-flex gap-2">
                        <button id="scanBtn" class="btn btn-primary flex-grow-1">
                            <i class="fas fa-play me-2"></i>开始扫描
                        </button>
                        <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#scheduleModal">
                            <i class="fas fa-clock me-2"></i>定时任务
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div id="progress" class="card mb-4 d-none">
            <div class="card-body p-3">
                <div class="d-flex align-items-center">
                    <div class="spinner-border text-primary me-3" role="status">
                        <span class="visually-hidden">扫描中...</span>
                    </div>
                    <div class="flex-grow-1">
                        <div class="progress">
                            <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar"></div>
                        </div>
                        <small class="text-muted mt-1 d-block">正在扫描中，请稍候...</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th>状态</th>
                                <th>IP地址</th>
                                <th>设备类型</th>
                                <th>响应时间</th>
                                <th>开放端口</th>
                                <th class="text-end">操作</th>
                            </tr>
                        </thead>
                        <tbody id="results">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 设备详情模态框 -->
        <div class="modal fade" id="deviceModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">设备详情</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">设备类型</label>
                                    <div id="deviceType" class="form-control-plaintext"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">IP地址</label>
                                    <div id="deviceIp" class="form-control-plaintext"></div>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">开放端口</label>
                            <div id="openPorts" class="form-control-plaintext"></div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">设备信息</label>
                            <pre id="deviceInfo" class="bg-light p-3 rounded"></pre>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" onclick="openWebInterface()">
                            <i class="fas fa-external-link-alt me-2"></i>打开Web界面
                        </button>
                        <button type="button" class="btn btn-success" onclick="copyRtspUrl()">
                            <i class="fas fa-copy me-2"></i>复制RTSP地址
                        </button>
                        <button type="button" class="btn btn-secondary" onclick="testDevice()">
                            <i class="fas fa-vial me-2"></i>测试设备
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 定时任务模态框 -->
        <div class="modal fade" id="scheduleModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">定时任务</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <button class="btn btn-primary w-100" data-bs-toggle="modal" data-bs-target="#addScheduleModal">
                                <i class="fas fa-plus me-2"></i>添加定时任务
                            </button>
                        </div>
                        <div id="taskList" class="list-group">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加定时任务模态框 -->
        <div class="modal fade" id="addScheduleModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">添加定时任务</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="scheduleForm">
                            <div class="mb-3">
                                <label class="form-label">网段</label>
                                <input type="text" class="form-control" name="network" required placeholder="192.168.1.0/24">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">执行时间</label>
                                <input type="time" class="form-control" name="time" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">重复</label>
                                <select class="form-select" name="repeat">
                                    <option value="daily">每天</option>
                                    <option value="weekly">每周</option>
                                    <option value="monthly">每月</option>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-primary w-100">保存</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let deviceModal = new bootstrap.Modal(document.getElementById('deviceModal'));
        let scheduleModal = new bootstrap.Modal(document.getElementById('scheduleModal'));
        let addScheduleModal = new bootstrap.Modal(document.getElementById('addScheduleModal'));

        document.getElementById('scanBtn').addEventListener('click', async () => {
            const network = document.getElementById('network').value;
            if (!network) {
                alert('请输入要扫描的网段！');
                return;
            }

            // 显示进度条
            document.getElementById('progress').classList.remove('d-none');
            document.getElementById('scanBtn').disabled = true;

            try {
                const response = await fetch('/scan', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ network })
                });

                if (!response.ok) {
                    throw new Error('扫描失败');
                }

                const data = await response.json();
                updateResults(data);
            } catch (error) {
                alert('扫描出错：' + error.message);
            } finally {
                document.getElementById('progress').classList.add('d-none');
                document.getElementById('scanBtn').disabled = false;
            }
        });

        function updateResults(data) {
            const tbody = document.getElementById('results');
            tbody.innerHTML = '';

            if (!data.devices || !Array.isArray(data.devices)) {
                console.error('Invalid data format:', data);
                return;
            }

            data.devices.forEach(device => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>
                        <span class="badge ${device.status === 'active' ? 'bg-success' : 'bg-danger'}"
                              title="${device.status === 'active' ? '在线' : '离线'}">
                              ${device.status === 'active' ? '在线' : '离线'}
                        </span>
                    </td>
                    <td>${device.ip}</td>
                    <td>${device.device_type || '未知'}</td>
                    <td>${device.response_time ? device.response_time + 'ms' : '-'}</td>
                    <td>
                        ${(device.open_ports || []).map(port => 
                            `<span class="badge bg-success">${port}</span>`
                        ).join(' ')}
                    </td>
                    <td class="text-end">
                        <button class="btn btn-sm btn-outline-primary" onclick='showDeviceDetails(${JSON.stringify(device)})'>
                            <i class="fas fa-info-circle"></i>
                        </button>
                    </td>
                `;
                tbody.appendChild(tr);
            });

            if (data.message) {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td colspan="6" class="text-center text-muted">
                        ${data.message}
                    </td>
                `;
                tbody.appendChild(tr);
            }
        }

        function showDeviceDetails(device) {
            // 更新设备详情模态框内容
            document.getElementById('deviceType').textContent = device.device_type || '未知';
            document.getElementById('deviceIp').textContent = device.ip;
            document.getElementById('openPorts').textContent = (device.open_ports || []).join(', ') || '无';
            
            // 构建设备信息
            const info = {
                '设备状态': device.status === 'active' ? '在线' : '离线',
                '响应时间': device.response_time ? `${device.response_time}ms` : '未知',
                '设备型号': device.model || '未知',
                '固件版本': device.firmware || '未知',
                '认证信息': device.auth_info || '未知'
            };
            
            document.getElementById('deviceInfo').textContent = 
                Object.entries(info)
                    .map(([key, value]) => `${key}: ${value}`)
                    .join('\n');
            
            // 显示模态框
            deviceModal.show();
        }

        function openWebInterface() {
            const ip = document.getElementById('deviceIp').textContent;
            const ports = document.getElementById('openPorts').textContent.split(',').map(p => parseInt(p.trim()));
            
            // 优先使用80或8000端口
            const webPort = ports.find(p => p === 80 || p === 8000) || ports[0];
            if (webPort) {
                window.open(`http://${ip}:${webPort}`);
            } else {
                alert('未找到可用的Web端口');
            }
        }

        // Schedule Form Handling
        document.getElementById('scheduleForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = {
                network: formData.get('network'),
                time: formData.get('time'),
                repeat: formData.get('repeat')
            };

            try {
                const response = await fetch('/api/schedule', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                if (!response.ok) {
                    throw new Error('添加定时任务失败');
                }

                addScheduleModal.hide();
                loadScheduledTasks();
            } catch (error) {
                alert('添加定时任务失败：' + error.message);
            }
        });

        function loadScheduledTasks() {
            fetch('/api/schedules')
                .then(response => response.json())
                .then(tasks => {
                    const taskList = document.getElementById('taskList');
                    taskList.innerHTML = '';

                    tasks.forEach(task => {
                        const div = document.createElement('div');
                        div.className = 'list-group-item';
                        div.innerHTML = `
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">${task.network}</h6>
                                    <small class="text-muted">
                                        ${task.time} | ${task.repeat === 'daily' ? '每天' : 
                                                       task.repeat === 'weekly' ? '每周' : '每月'}
                                    </small>
                                </div>
                                <button class="btn btn-sm btn-outline-danger" onclick="removeTask('${task.id}')">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        `;
                        taskList.appendChild(div);
                    });
                })
                .catch(error => {
                    console.error('加载定时任务失败:', error);
                    alert('加载定时任务失败');
                });
        }

        function removeTask(taskId) {
            if (!confirm('确定要删除这个定时任务吗？')) {
                return;
            }

            fetch(`/api/schedule/${taskId}`, { method: 'DELETE' })
                .then(response => {
                    if (response.ok) {
                        loadScheduledTasks();
                    } else {
                        throw new Error('删除任务失败');
                    }
                })
                .catch(error => alert('删除任务失败：' + error.message));
        }

        // Load tasks on page load
        loadScheduledTasks();
    </script>
</body>
</html>
